package org.example;

public class Test4 {
    //leetcode 235 二叉搜索树的最近公共祖先 https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/submissions/542837418/
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        if (root == p || root == q) return root;
        if ((p.val < root.val && root.val < q.val) || (p.val > root.val && root.val > q.val)) {
            return root;
        }else if (p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor(root.left,p,q);
        }else {
            return lowestCommonAncestor(root.right,p,q);
        }
    }
}
